437D - The Child and Zoo - CodeForces Solution


dsu sortings *1900

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>
using namespace std;
#define f first
#define s second

const int mxn = 1e5+10 ;
int l[mxn] , sz[mxn] ;

inline get(int v){
	return (l[v]==v?v :l[v] = get(l[v])) ;
} 


inline DSU(int v , int u){
	if(sz[u] > sz[v]) swap(v,u) ;
	sz[v] += sz[u] ;
	sz[u] = 0 ;
	l[u] = v ;
	
	return 0 ;
}

int main(){
	ios_base::sync_with_stdio(false); cin.tie(0);
	
	//input:
	int n , m ;
	cin >> n >> m ;
	
	//update arr sz & l:
	for(int i = 0 ; i < n ; i ++ ){
		sz[i] = 1 ;
		l[i] = i ;
	}
	
	//input (weight):
	int a[n] ;
	for(int i = 0 ; i < n ; i ++ ) cin >> a[i] ;
	
	
	//update pair:
	pair<int,pair<int,int>> edge[m] ;  //{weight,{endpoints}}
	for(int i = 0 ; i < m ; i ++){
		int v , u ;
		cin >> v >> u ;
		v--; u--;
		int mn = min(a[v],a[u]) ;
		edge[i] = make_pair(mn , make_pair(v,u)) ;
	}
	
	//solve:
	long double sum = 0 ;
	sort(edge,edge+m);
	for(int i = m-1 ; i >= 0 ; i --){
		int v = edge[i].s.f ;
		int u = edge[i].s.s ;
		int w = edge[i].f;
		
		v = get(v) ;
		u = get(u) ;
		if( v != u ){
			long double x = (long double)sz[v]*sz[u]*w ;
			sum += x ;
			DSU(v,u) ;
		}
	}
	
	cout << setprecision(6) << fixed;
	cout << (sum*2)/((long double)n*(n-1)) ;
}


Comments

Submit
0 Comments
More Questions

1325D - Ehab the Xorcist
552B - Vanya and Books
1722E - Counting Rectangles
168A - Wizards and Demonstration
168B - Wizards and Minimal Spell
7A - Kalevitch and Chess
912B - New Year's Eve
1537C - Challenging Cliffs
879B - Table Tennis
1674E - Breaking the Wall
1282A - Temporarily unavailable
1366C - Palindromic Paths
336A - Vasily the Bear and Triangle
926A - 2-3-numbers
276D - Little Girl and Maximum XOR
1253C - Sweets Eating
1047A - Little C Loves 3 I
758D - Ability To Convert
733A - Grasshopper And the String
216A - Tiling with Hexagons
1351B - Square
1225A - Forgetting Things
1717A - Madoka and Strange Thoughts
1717B - Madoka and Underground Competitions
61B - Hard Work
959B - Mahmoud and Ehab and the message
802G - Fake News (easy)
1717C - Madoka and Formal Statement
420A - Start Up
1031A - Golden Plate